#include "app_router.h"
#include "app_mqtt.h"
#include "thirdparty/log.c/log.h"
#include "app_message.h"
#include <stdlib.h>

#define MAX_DEVICE_NUM 10

static Device **device_list;
static int device_list_size = 0;

/**
 * @brief MQTT回调函数
 *
 * @param json_str MQTT收到的字符串
 * @return int 0成功 -1失败
 */
static int app_router_mqttCallback(char *json_str)
{
    // 将Json str转化为二进制格式写到特定设备
    Message message;
    unsigned char binary_data[128];
    if (app_message_initByJsonStr(&message, json_str) < 0)
    {
        log_warn("Message Init Failed");
        return -1;
    }
    int len = app_message_saveBinary(&message, binary_data, 128);
    app_message_free(&message);
    if (len < 0)
    {
        log_warn("Message Save Binary Failed");
        return -1;
    }
    for (int i = 0; i < device_list_size; i++)
    {
        // 我们规定一种连接只有一个设备与之对应
        if (device_list[i]->connection_type == message.connection_type)
        {
            // 找到对应的设备，发送数据
            return app_device_write(device_list[i], binary_data, len);
        }
    }
    log_warn("No device found for message %s", json_str);
    return -1;
}

static int app_router_deviceCallback(Device *device, void *data, int len)
{
    Message message;
    char buf[128];
    if (app_message_initByBinary(&message, device->connection_type, data, len) < 0)
    {
        log_warn("Message Init Failed");
        return -1;
    }
    int result = app_message_saveJson(&message, buf, 128);
    app_message_free(&message);
    if (result < 0)
    {
        log_warn("Message Save Json Failed");
        return -1;
    }
    return app_mqtt_send(buf);
}

int app_router_init()
{
    // 初始化MQTT客户端
    if (app_mqtt_init())
    {
        log_error("MQTT Client Init Failed");
        return -1;
    }
    app_mqtt_registerRecvCallback(app_router_mqttCallback);

    // 初始化设备列表
    device_list = malloc(sizeof(Device *) * MAX_DEVICE_NUM);
    if (device_list == NULL)
    {
        log_error("Device List Init Failed");
        return -1;
    }
    device_list_size = 0;

    return 0;
}

int app_router_resigerDevice(Device *device)
{
    // 向列表中添加设备
    if (device_list_size >= MAX_DEVICE_NUM)
    {
        log_error("Device List Full");
        return -1;
    }

    device_list[device_list_size++] = device;
    app_device_registerRecvCallback(device, app_router_deviceCallback);
    app_device_start(device);
    return 0;
}

void app_router_close()
{
    log_info("Close Router");
    // 首先关闭设备
    for (int i = 0; i < device_list_size; i++)
    {
        app_device_stop(device_list[i]);
        app_device_close(device_list[i]);
    }

    // 清理消息了路由内存
    free(device_list);
    device_list_size = 0;
    // 关闭MQTT客户端
    app_mqtt_close();
}
